package com.stu.controller;

import com.stu.service.MsmService;
import com.stu.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信验证码
    @PostMapping("send/{phone}")
    public Map sendMsm(@PathVariable("phone") String phone){
        String code = null;

        //0.从 redis中是查询验证码，有了就直接用
        ValueOperations<String,String> operations = redisTemplate.opsForValue();
        boolean hasKey = redisTemplate.hasKey(phone);

        if(!hasKey) {

            //1. RandomUtil 生成验证码
            code = RandomUtil.getFourBitRandom();
            System.out.println("生成的验证码code为：" + code);
            Map<String, Object> param = new HashMap<>();
            param.put("code", code);

            //2. 调用 service发送短信
//            boolean isSend = msmService.send(param, phone);
//            System.out.println("service发送短信是否成功：" + isSend);

            //3.存验证码到 redis中，设置生命周期 5min
//            if (isSend)
                redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        }else {
            code = operations.get(phone);
            System.out.println("从redis中获得code：" + code);
        }

        Map<String,String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);

        return map;
    }

    //从 redis中查询验证码是否存在
    @PostMapping("checkCode")
    public String checkCodeFromRedis(String userTelno){
        String code = null;

        ValueOperations<String,String> operations = redisTemplate.opsForValue();
        boolean hasKey = redisTemplate.hasKey(userTelno);

        if(hasKey) {
            code = operations.get(userTelno);
            System.out.println("从redis中获得code：" + code);
        }
        return code;
    }
}
